package server

import (
	"context"
	"gitee.com/smallow/srpc/infrastructure/business"
	"gitee.com/smallow/srpc/infrastructure/model"
	"gitee.com/smallow/srpc/infrastructure/proto/pb"
	"github.com/pkg/errors"
	"log"
)

type CompanyService struct{}

const (
	ISCompanyService  = "CompanyService"
	MCS_CreateCompany = "CreateCompany"
	MCS_FindCompany   = "FindCompany"

	MCS_SettingCM = "SettingCM"
	MCS_CreateDep = "CreateDepartment"
	MCS_SettingDM = "SettingDM"
)

/* 创建公司  */
func (c *CompanyService) CreateCompany(ctx context.Context, req *pb.CreateCompanyReq) (*pb.CreateCompanyResp, error) {
	if req.AppID == "" {
		return &pb.CreateCompanyResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	company := &model.Company{
		BaseModel:     model.BaseModel{AppID: req.AppID},
		Name:          req.Name,
		ShortName:     req.ShortName,
		Address:       req.Address,
		ContactPerson: req.ContactPerson,
		ContactPhone:  req.ContactPhone,
		CompanyType:   uint8(req.CompanyType),
		State:         uint8(req.State),
		AuthState:     0,
	}
	existCompany := business.FindCompanyBy(&model.Company{Name: req.Name})
	if existCompany.ID != 0 {
		log.Printf("创建公司: [%s]公司名称已存在", req.Name)
		return &pb.CreateCompanyResp{
			Success:   false,
			CompanyID: 0,
			Message:   "",
		}, errors.New("公司名称已存在")
	}
	err := business.SaveCompany(company)
	if err != nil {
		log.Printf("创建公司: [%s]创建失败 错误:%s", req.Name, err)
		return &pb.CreateCompanyResp{
			Success:   false,
			CompanyID: 0,
			Message:   "创建失败",
		}, err
	} else {
		log.Printf("创建公司: [%s]创建成功 ", req.Name)
		return &pb.CreateCompanyResp{
			Success:   true,
			CompanyID: int32(company.ID),
			Message:   "创建成功",
		}, nil
	}

}

/* 根据公司id查找公司  */
func (c *CompanyService) FindCompany(ctx context.Context, req *pb.FindCompanyReq) (*pb.FindCompanyResp, error) {
	if req.CompanyID == 0 || req.AppID == "" {
		return &pb.FindCompanyResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	where := &model.Company{
		BaseModel: model.BaseModel{ID: int(req.CompanyID), AppID: req.AppID},
	}
	company, err := business.FindCompanyByID(where)
	company_ := &pb.Company{}
	if err != nil {
		log.Printf("查找公司信息出错：公司id[%d] appid[%s] 错误[%s]", req.CompanyID, req.AppID, err.Error())
		return &pb.FindCompanyResp{
			Success: false,
			Message: "查找公司信息出错",
		}, err
	} else {
		company_ = &pb.Company{
			Id:            int32(company.ID),
			Name:          company.Name,
			ContactPerson: company.ContactPerson,
			ContactPhone:  company.ContactPhone,
			ShortName:     company.ShortName,
			Address:       company.Address,
			CompanyType:   pb.CompanyType(company.CompanyType),
			AppID:         company.AppID,
			CreateAt:      company.CreateAt.String(),
			State:         int32(company.State),
			AuthState:     int32(company.AuthState),
		}
	}
	departments, err2 := business.FindDep(&model.Department{CompanyID: int(req.CompanyID), BaseModel: model.BaseModel{AppID: req.AppID}})
	var departments_ []*pb.DepartmentStruct
	if err2 != nil {
		log.Printf("查找公司下的部门出错：公司id[%d] appid[%s] 错误[%s]", req.CompanyID, req.AppID, err2.Error())
		return &pb.FindCompanyResp{
			Success: false,
			Message: "查找公司下的部门出错",
		}, err
	} else {
		for _, v := range *departments {
			departments_ = append(departments_, &pb.DepartmentStruct{
				Id:         int32(v.ID),
				Name:       v.Name,
				ShotName:   v.ShortName,
				ParentID:   int32(v.ParentID),
				ParentName: v.ParentName,
				State:      int32(v.State),
				CompanyID:  int32(v.CompanyID),
				AppID:      v.AppID,
			})
		}
	}

	return &pb.FindCompanyResp{
		Company:     company_,
		Departments: departments_,
		Success:     true,
	}, nil

}

/* 查找公司及账户信息*/
func (c *CompanyService) FindCompanyAccount(ctx context.Context, req *pb.FindCompanyReq) (*pb.FindCompanyAccountResp, error) {
	if req.CompanyID == 0 || req.AppID == "" {
		return &pb.FindCompanyAccountResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	where := &model.CompanyView{
		Company: model.Company{BaseModel: model.BaseModel{ID: int(req.CompanyID), AppID: req.AppID}},
	}
	companyView, err := business.FindCompany(where)
	companyAccount_ := &pb.CompanyAccount{}
	if err != nil {
		log.Printf("查找公司及账户信息出错：公司id[%d] appid[%s] 错误[%s]", req.CompanyID, req.AppID, err.Error())
		return &pb.FindCompanyAccountResp{
			Success: false,
			Message: "查找公司及账户信息出错",
		}, err
	} else {
		companyAccount_ = &pb.CompanyAccount{
			Id:               int32(companyView.ID),
			Name:             companyView.Name,
			ContactPerson:    companyView.ContactPerson,
			ContactPhone:     companyView.ContactPhone,
			ShortName:        companyView.ShortName,
			Address:          companyView.Address,
			CompanyType:      pb.CompanyType(companyView.CompanyType),
			AppID:            companyView.AppID,
			CreateAt:         companyView.CreateAt.String(),
			State:            int32(companyView.State),
			AuthState:        int32(companyView.AuthState),
			AccountBindPhone: companyView.AccountBindPhone,
			AccountNickName:  companyView.AccountNickName,
			AccountState:     int32(companyView.AccountState),
		}
	}

	var departments_ []*pb.DepartmentStruct
	departments, err2 := business.FindDep(&model.Department{CompanyID: int(req.CompanyID), BaseModel: model.BaseModel{AppID: req.AppID}})
	if err2 != nil {
		log.Printf("查找公司下的部门出错：公司id[%d] appid[%s] 错误[%s]", req.CompanyID, req.AppID, err2.Error())
		return &pb.FindCompanyAccountResp{
			Success: false,
			Message: "查找公司下的部门出错",
		}, err
	} else {
		for _, v := range *departments {
			departments_ = append(departments_, &pb.DepartmentStruct{
				Id:         int32(v.ID),
				Name:       v.Name,
				ShotName:   v.ShortName,
				ParentID:   int32(v.ParentID),
				ParentName: v.ParentName,
				State:      int32(v.State),
				CompanyID:  int32(v.CompanyID),
				AppID:      v.AppID,
			})
		}
	}
	return &pb.FindCompanyAccountResp{
		CompanyAccount: companyAccount_,
		Departments:    departments_,
		Success:        true,
	}, nil

}

/* 创建公司账户 */
func (c *CompanyService) CreateCA(ctx context.Context, req *pb.CreateCAReq) (*pb.CreateCAResp, error) {
	account := &model.Account{
		BaseModel:     model.BaseModel{AppID: req.AppID},
		BodyID:        int(req.BodyID),
		BodyType:      1, //'账号主体类型1-公司,2-人员,3-部门',
		State:         uint8(req.State),
		BindPhone:     req.BindPhone,
		NickName:      req.NickName,
		AccountNumber: req.AccountNumber,
		Password:      business.GetMd5String(req.Password),
		WxOpenID:      req.WxOpenID,
		AliPayID:      req.AliPayID,
	}
	// 判断账号主体是否已存在账号
	if business.ExistAccount(&model.Account{BodyID: account.BodyID, BodyType: account.BodyType}) {
		log.Printf("创建公司账户出错：公司id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "该主体已存在其他账号")
		return &pb.CreateCAResp{Success: false, Message: "该主体已存在其他账号"}, nil
	}
	// 判断账号是否重复
	if business.ExistAccount(&model.Account{AccountNumber: req.AccountNumber}) {
		log.Printf("创建公司账号出错：公司id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "该账号名已存在")
		return &pb.CreateCAResp{Success: false, Message: "该账号名已存在"}, nil
	}
	// 判断手机号是否已存在
	if business.ExistPhone(account.BindPhone) {
		log.Printf("创建公司账户出错：公司id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "手机号已绑定其他账号")
		return &pb.CreateCAResp{Success: false, Message: "手机号已绑定其他账号"}, nil
	}
	// 创建   1- 公司管理员
	err := business.CreateAccountInfo(account, 1)
	if err == nil {
		return &pb.CreateCAResp{
			Success: true,
			Message: "创建成功",
		}, nil
	} else {
		log.Printf("创建公司账户出错：公司id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, err.Error())
		return &pb.CreateCAResp{
			Success: false,
			Message: "创建失败",
		}, nil
	}

}

/*更新公司信息*/
func (c *CompanyService) UpdateCompany(ctx context.Context, req *pb.UpdateCompanyReq) (*pb.UpdateCompanyResp, error) {
	if req.Id == 0 || req.AppID == "" {
		return &pb.UpdateCompanyResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	existCompany1 := business.FindCompanyBy(&model.Company{BaseModel: model.BaseModel{ID: int(req.Id)}})
	if existCompany1.ID == 0 {
		return &pb.UpdateCompanyResp{
			Success: false,
			Message: "无效的id",
		}, errors.New("无效的id")
	}
	existCompany := business.FindCompanyBy(&model.Company{Name: req.Name})
	if existCompany.ID != 0 && existCompany.ID != int(req.Id) {
		log.Printf("创建公司: [%s]公司名称已存在", req.Name)
		return &pb.UpdateCompanyResp{
			Success: false,
			Message: "公司名称已存在",
		}, errors.New("公司名称已存在")
	}
	company := &model.Company{
		BaseModel:     model.BaseModel{AppID: req.AppID, ID: int(req.Id)},
		Name:          req.Name,
		ShortName:     req.ShortName,
		Address:       req.Address,
		ContactPerson: req.ContactPerson,
		ContactPhone:  req.ContactPhone,
		CompanyType:   uint8(req.CompanyType),
		State:         uint8(req.State),
		AuthState:     uint8(req.AuthState),
	}
	err := business.SaveCompany(company)
	if err != nil {
		return &pb.UpdateCompanyResp{
			Success: false,
			Message: "更新失败",
		}, err
	}
	return &pb.UpdateCompanyResp{
		Success: true,
	}, nil
}

/*删除公司信息
会删除公司及公司账户，部门及部门账户，人员及人员账户
*/
func (c *CompanyService) DeleteCompany(ctx context.Context, req *pb.DeleteCompanyReq) (*pb.DeleteCompanyResp, error) {
	if req.Id == 0 || req.AppID == "" {
		return &pb.DeleteCompanyResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	where := &model.Company{BaseModel: model.BaseModel{ID: int(req.Id), AppID: req.AppID}}
	existCompany1 := business.FindCompanyBy(where)
	if existCompany1.ID == 0 {
		return &pb.DeleteCompanyResp{
			Success: false,
			Message: "无效的id",
		}, errors.New("无效的id")
	}

	err := business.DeleteCompany(where)
	if err != nil {
		return &pb.DeleteCompanyResp{
			Success: false,
			Message: "删除失败",
		}, err
	}
	return &pb.DeleteCompanyResp{
		Success: true,
	}, nil
}

func Success() *pb.CommonResponse {
	return &pb.CommonResponse{Success: true, Code: 200, Message: "success"}
}

func AppIDEmptyError() (*pb.CommonResponse, error) {
	return &pb.CommonResponse{Success: false, Code: 100, Message: "AppID为空"}, errors.New("AppID为空")
}

func FailWithDetail(code int32, message string, err error) (*pb.CommonResponse, error) {
	return &pb.CommonResponse{Success: false, Code: code, Message: message}, err
}
